package threadSynchronization;

/**
 * @Author: WanqingLiu
 * @Date: 2023/02/02/15:51
 * 化妆模拟死锁
 */
public class DeadLock {

    public static void main(String[] args) {
        Makeup girl1 = new Makeup(0, "晚晴");
        Makeup girl2 = new Makeup(1, "婉晴");
        girl2.start();
        girl1.start();
    }
}
// 口红类
class LipStick{

}
// 镜子
class Mirror{

}
// 化妆线程
class Makeup extends Thread {
    static LipStick lipStick = new LipStick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;

    public Makeup(int choice, String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        // 化妆操作
        try {
            makeup();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void makeup() throws InterruptedException {
        if(choice == 0){ // 口红
            synchronized (lipStick) {
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000); // 一秒钟之后，她想获得镜子的锁
            }
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
            }
        } else { // 镜子
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(1000); // 一秒钟之后，她想获得口红的锁
            }
            synchronized (lipStick) {
                System.out.println(this.girlName + "获得口红的锁");
            }
        }
    }
}
